// pages/productdetails/productdetails.js
var app = getApp()
var WxParse = require('../../wxParse/wxParse.js');
const { domain } = app.globalData;

Page({
  data: {
    domain: domain,
    tabs: ["商品详情", "商品评价"],
    sliderOffset: 0,
    sliderLeft: 0,
    activeIndex: 0,
    choiceStyleHidden: true,
    isGroupbuying: false,
    gourpbuyingSum: 0,
    groupbuyingList: [],
    groupbuyingGoods: {},
    shareTitle: '',
  },
  
  onShareAppMessage: function (res) {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '热马品牌商城小程序',
      path: '/pages/goodsDetail/goodsDetail?goods_id=' + that.data.goods_id + '&share_id=' + wx.getStorageSync('user_id'),
      imageUrl: "/pages/images/logo.png",
      success: function (res) {
        // 转发成功
        wx.showToast({
          title: '转发成功！',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  tabClick: function (e) {
    this.setData({
      activeIndex: e.currentTarget.id
    });
  },

  //拨打电话
  makePhone: function () {
    wx.makePhoneCall({
      phoneNumber: '18026409791',
    })
  },

  //购物车点击事件
  cartClick: function () {
    wx.switchTab({
      url: '../cart/cart',
    })
  },

  //首页点击事件
  indexClick: function () {
    wx.switchTab({
      url: '../index/index',
    })
  },
  choiceStyle: function (e) {
    var id1 = e.currentTarget.dataset.myid;
    var id2 = e.currentTarget.id;
    var style = this.data.product.style;

    for (var i = 0; i < style.length; i++) {
      for (var j = 0; j < style[i].values; j++) {
        style[i].values[j].isChoosed = 0;
      }
    }
    for (var i = 0; i < style.length; i++) {
      if (id1 == style[i].id) {
        for (var j = 0; j < style[i].values; j++) {
          if (id2 == style[i].values[j].id) {
            style[i].values[j].isChoosed = 1;
          }
        }
      }
    }
    var product = this.data.product;
    product.style = style;
    this.setData({ product: product });
  },
  setStyleHidden: function () {
    this.setData({
      modelHidden: false
    })
  },
  formatDate: function (str) {
    var now = new Date(parseInt(str) * 1000);
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    return year + "年" + this.fixZero(month, 2) + "月" + this.fixZero(date, 2) + "日";
  },
  fixZero: function (num, length) {
    var str = "" + num;
    var len = str.length; var s = "";
    for (var i = length; i-- > len;) {
      s += "0";
    }
    return s + str;
  },

  onLoad: function (option) {
    var thiz = this
    app.login({
      share_id: option.share_id
    })
    wx.getSystemInfo({
      success: function (res) {
        thiz.setData({
          hiddenLoading: true,
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth,
          goods_id: option.goods_id,
          modelHidden: true
        });
      }
    })

    thiz.setData({
      inv_i: app.globalData.inv_i
    })
    thiz.loadData(option.goods_id);

    wx.showShareMenu({
      withShareTicket: true
    })
  },

  /* 商品读取 */
  loadData: function (key) {
    var thiz = this
    var PageInterface = app.globalData.domain + app.globalData.PageInterface
    var domain = app.globalData.domain

    var goods_amount = 1;
    //圆角显示的数量
    var total_goods_amount = 0;

    wx.request({
      url: PageInterface,
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      data: {
        format_type: 'json',
        api_cate: 'Goods',
        api: 4015,
        id: key
      },
      success: function (res) {
        if (res.data.data.msg) {
          thiz.loadData()
        } else {
          /*图片*/
          res.data.data.img.forEach(function (element, index) {
            element.goods_imgurl = domain + element.goods_imgurl
          })
          res.data.data.default_img = domain + res.data.data.default_img
          res.data.data.img.reverse()
          res.data.data.img.push({
            goods_img_id: 0,
            goods_id,
            goods_imgurl: res.data.data.default_img,
          })
          res.data.data.img.reverse()

          var active_goods_options = [];

          if (res.data.data.all_spec) {

            res.data.data.all_spec.forEach(function (element, index) {
              if (element.checked == 1) {
                active_goods_options.push(element)
              }
            })
          }

          if (res.data.data.spec) {
            res.data.data.spec.forEach(function (element, index) {
              element.spec_item.reverse()
              element.spec_item.forEach(function (each, eachIndex) {
                each.status = false
              })
            })
          }

          WxParse.wxParse('goods_describe', 'html', res.data.data.goods_describe, thiz, 0);

          const { goods_id, market_price, price, stock } = res.data.data;

          if (!active_goods_options.length) {
            active_goods_options.push({
              goods_id,
              market_price,
              option_title: "默认",
              price,
              stock,
            })
          }

          total_goods_amount = thiz.cart_count();

          thiz.setData({
            hiddenLoading: true,
            active_goods_options: active_goods_options[0],
            spec_totolPrice: active_goods_options[0].price,
            goods_detail: res.data.data,
            activeSpec: [],
            specOption: active_goods_options.specs,
            goods_amount: goods_amount,
            total_goods_amount: total_goods_amount
          })
        }
      }
    })

  },

//判断是否相同规格
  contains: function (arr, id) {
    //while
    var i = arr.length;
    while (i--) {
      if (arr[i].active_goods_options.goods_option_id === id) {
        return i;
      }
    }
    return -1;
  },
//判断是否相同商品
  contains_goods: function (arr, id){
    //while
    var i = arr.length;
    while (i--) {
      if (arr[i].active_goods_options.goods_id === id) {
        return i;
      }
    }
    return -1;
  },



  //加入购物车
  addCart: function () {
    var thiz = this

    var goods_detail = this.data.goods_detail
    var amount = this.data.goods_amount
    var active_goods_options = this.data.active_goods_options
    //圆角显示的购物车所有商品数量
    var total_goods_amount = 0;
    var goods_info = {
      goods_detail: goods_detail,
      active_goods_options: active_goods_options,
      amount: amount
    }
    wx.getStorage({
      key: 'cartStorage',
      success: function (res) {
        if (res.data.length > 0) {
          var index = thiz.contains(res.data, active_goods_options.goods_option_id)
          var index2 = thiz.contains_goods(res.data, active_goods_options.goods_id)

          if (index2 == -1 || index == -1 ) {
            res.data.push(goods_info)
          } else {
            res.data[index].amount += amount
          }
          console.log('data',res.data);
          wx.setStorageSync('cartStorage', res.data)
          wx.showToast({
            title: '加入购物车成功',
          });

        } else {

          res.data.push(goods_info);
          wx.setStorageSync('cartStorage', res.data)
          wx.showToast({
            title: '加入购物车成功',
          })
        }
        total_goods_amount = thiz.cart_count();
        thiz.setData({
          modelHidden: true,
          total_goods_amount: total_goods_amount
        })
      },
    })
  },

  getOrderInfo(event) {
    const type = event.currentTarget.dataset.type;
    var goods_detail = this.data.goods_detail
    var amount = this.data.goods_amount
    var active_goods_options = this.data.active_goods_options
    goods_detail.goods_describe = ""
    var obj = {
      goods_detail: goods_detail,
      active_goods_options: active_goods_options,
      amount: amount
    }
    var obj2 = {
      amount: amount,
      checked: true,
      goods_option_id: active_goods_options.id,
      id: goods_detail.goods_id,
      img_url: goods_detail.default_img,
      name: goods_detail.goods_name,
      price: active_goods_options.price,
      size: active_goods_options.option_title
    };
    var postGoods = [];
    var pay_goods = [];
    postGoods.push(obj);
    pay_goods.push(obj2);
    var str = JSON.stringify(postGoods);
    var str2 = JSON.stringify(pay_goods);
    var totalPrice = amount * (type ? this.data.groupbuyingGoods.price : active_goods_options.price);
    return {
      str: str,
      str2: str2,
      totalPrice: totalPrice
    }
  },

  //提交订单
  postOrder: function (event) {
    if (!app.globalData.inv_i) {
      wx.navigateTo({
        url: '../login/login',
      })
    }else{
      const type = event.currentTarget.dataset.type,
        result = type ? '&type=groupbuying' : '';
      const { str, str2, totalPrice } = this.getOrderInfo(event);
      wx.navigateTo({
        url: '../cartConfirm/cartConfirm?postGoods=' + str + '&pay_goods=' + str2 + '&totalPrice=' + totalPrice + result
      })
    }
  },

  //关闭规格选择
  closeModal: function () {
    var thiz = this
    thiz.setData({
      modelHidden: !thiz.data.modelHidden
    })
  },

  //规格数量增加
  goodsAddClick: function () {
    var thiz = this

    thiz.data.goods_amount++

    var active_goods_options = thiz.data.active_goods_options

    var totalPrice = active_goods_options.price * thiz.data.goods_amount

    this.setData({
      spec_totolPrice: totalPrice,
      goods_amount: thiz.data.goods_amount
    })
  },

  //规格数量减少
  goodsReduceClick: function () {
    var thiz = this

    if (thiz.data.goods_amount > 1) {
      thiz.data.goods_amount--;
    }
    var active_goods_options = thiz.data.active_goods_options

    var totalPrice = active_goods_options.price * thiz.data.goods_amount

    this.setData({
      spec_totolPrice: totalPrice,
      goods_amount: thiz.data.goods_amount
    })
  },

  //规格选择
  spec_itemClick: function (e) {
    var thiz = this
    var id = e.currentTarget.dataset.id
    var spec = thiz.data.goods_detail.spec

    var selectSpec_id = e.currentTarget.dataset.spec;
    var activeSpec = thiz.data.activeSpec

    spec.forEach(function (element, index) {
      if (element.goods_spec_id == selectSpec_id) {
        element.spec_item.forEach(function (each, eachIndex) {
          if (each.goods_item_id == id) {
            each.status = true

          } else {
            each.status = false
          }
        })
      }
    })

    if (activeSpec.length > 0) {

      if (thiz.containsSpec(activeSpec, selectSpec_id) == -1) {
        activeSpec.push({
          selectSpec_id: selectSpec_id,
          id: id
        })
      } else {
        if (thiz.containsId(activeSpec, id) == -1) {

          activeSpec.splice(thiz.containsSpec(activeSpec, selectSpec_id), 1)

          activeSpec.push({
            selectSpec_id: selectSpec_id,
            id: id
          })
        } else {
          activeSpec.splice(thiz.containsId(activeSpec, id), 1)
        }
      }
    } else {
      activeSpec.push({
        selectSpec_id: selectSpec_id,
        id: id
      })
    }

    var array = [];
    var stock, price;

    if (spec.length == 1) {

      thiz.data.goods_detail.all_spec.forEach(function (element, index) {
        if (element.specs.indexOf(activeSpec[0].id) >= 0) {
          array.push(element)
        }
      })

      thiz.data.active_goods_options = array[0]
    }

    if (activeSpec.length == 2) {
      thiz.data.goods_detail.all_spec.forEach(function (element, index) {
        if (element.specs.indexOf(activeSpec[0].id) >= 0) {
          if (element.specs.indexOf(activeSpec[1].id) >= 0) {

            array.push(element)
          }
        }
      })

      thiz.data.active_goods_options = array[0]
    }

    thiz.setData({
      goods_detail: thiz.data.goods_detail,
      lastSpec: thiz.data.lastSpec,
      activeSpec: activeSpec,
      active_goods_options: thiz.data.active_goods_options,
      spec_totolPrice: thiz.data.active_goods_options.price,
      goods_amount: 1
    })

  },
  containsSpec: function (arr, id) {
    //while
    var i = arr.length;
    while (i--) {
      if (arr[i].selectSpec_id === id) {
        return i;
      }
    }
    return -1;
  },
  containsId: function (arr, id) {
    //while
    var i = arr.length;
    while (i--) {
      if (arr[i].id === id) {
        return i;
      }
    }
    return -1;
  },
  cart_count: function () {
    //购物车商品数量
    var total_goods_amount = 0;
    var cartStorage = wx.getStorageSync('cartStorage')
    if (cartStorage.length > 0) {
      cartStorage.forEach(function (element, index) {
        total_goods_amount += element.amount
      })
    }
    return total_goods_amount;
  },
  goToGetCoupon: function () {
    wx.navigateTo({
      url: '../getCoupon/getCoupon',
    })
  }
})